package panels;

import java.awt.CardLayout;
import java.awt.Color;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JSplitPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

import niso.DBHandler;
import niso.User;
import niso.userFrame;

public class ManageUser extends JSplitPane implements ItemListener, ActionListener,FocusListener,ListSelectionListener, KeyListener{

	
	private ArrayList<User> Users;
	private userFrame Parent; 
	private JTextField NameBox,AdduserBox;
	private JPasswordField PassBox,AddPass;
	private JComboBox UserTypeBox,UserBox,AddUserType,DelUserBox;
	private JButton AddBt,DelBt,SaveModificationsBt,AddMode,DelMode,UpdateMode;
	private String ChangeTest;
	private JComponent focus;
	private JPanel Right,DelPane;
	private JLabel ErrorAdd,ErrorMod,ErrorDel,CheckLbl;
	private GBPane Nav,AddPane,ModifyPane;
	private JList UserList;
	private CardLayout CL;
	
	
	public ManageUser(userFrame P){
		Parent=P;
		
		AddBt=new JButton("Add User");
		DelBt=new JButton("Remove User");
		SaveModificationsBt=new JButton("SaveModifications");
		
		Users=new ArrayList<User>();
		
		generateUIComponents();
		setComboBoxItems(UserTypeBox);
		setComboBoxItems(UserBox);
		
		if(Users.size()>0){
			NameBox.setText(Users.get(0).getUserName());
			PassBox.setText(Users.get(0).getUserPassword());
			UserTypeBox.setSelectedItem(Users.get(0).getusertype());
		}
		
		UserBox.addItemListener(this);
		UserTypeBox.addItemListener(this);
		AddBt.addActionListener(this);
		DelBt.addActionListener(this);
		NameBox.addFocusListener(this);
		PassBox.addFocusListener(this);
		SaveModificationsBt.addActionListener(this);
		SaveModificationsBt.setEnabled(false);
		AddMode.setEnabled(false);
		System.out.println("User: "+Parent.getUser().getUserName());
	}
	
	public void generateUIComponents(){
		/*set back to extends GBPane
		 * addComponent(new JLabel("Select User"), 0, 0, 1, 1, 0, 0, GridBagConstraints.NONE, GridBagConstraints.WEST);
		addComponent(UserBox=new JComboBox(), 1, 0, 2, 1, 0, 0, GridBagConstraints.HORIZONTAL, GridBagConstraints.WEST);
		addComponent(new JLabel("Name:"),0, 1, 1, 1, 0, 0, GridBagConstraints.NONE, GridBagConstraints.WEST);
		addComponent(NameBox=new JTextField(10), 1, 1, 1, 1, 0, 0, GridBagConstraints.NONE, GridBagConstraints.WEST);
		addComponent(new JLabel("Password:"),0, 2, 1, 1, 0, 0, GridBagConstraints.NONE, GridBagConstraints.WEST);
		addComponent(PassBox=new JPasswordField(10), 1, 2, 1, 1, 0, 0, GridBagConstraints.NONE, GridBagConstraints.WEST);
		addComponent(new JLabel("Type:"),0, 3, 1, 1, 0, 0, GridBagConstraints.NONE, GridBagConstraints.WEST);
		addComponent(UserTypeBox=new JComboBox(), 1, 3, 1, 1, 0, 0, GridBagConstraints.NONE, GridBagConstraints.WEST);
		addComponent(AddBt,2, 1, 1, 1, 0, 0, GridBagConstraints.HORIZONTAL, GridBagConstraints.WEST);
		addComponent(DelBt,2, 2, 1, 1, 0, 0, GridBagConstraints.HORIZONTAL, GridBagConstraints.WEST);
		addComponent(SaveModificationsBt,2, 3, 1, 1, 0, 0, GridBagConstraints.HORIZONTAL, GridBagConstraints.WEST);
		*/
		UserBox=new JComboBox();
		CL=new CardLayout();
		Right=new JPanel(CL);
		setRightComponent(Right);
		Nav=new GBPane();
		setLeftComponent(Nav);
		
		JLabel TitleAdd=new JLabel("User Account/s"),EnterInfo=new JLabel("Enter User Information"),SlctUser=new JLabel("Choose a user name");
		JTextField Line1=new JTextField();
		ErrorAdd=new JLabel("");
		AddPane=new GBPane();
		
		AddMode=new JButton("Add User/s");
		UpdateMode=new JButton("Update User/s");
		DelMode=new JButton("Remove User/s");
		
		Nav.addComponent(AddMode, 0, 0, 1, 1, 1, 1, GridBagConstraints.HORIZONTAL, GridBagConstraints.WEST);
		Nav.addComponent(UpdateMode, 0, 1, 1, 1, 1, 1, GridBagConstraints.HORIZONTAL, GridBagConstraints.WEST);
		Nav.addComponent(DelMode, 0, 2, 1, 1, 1, 1, GridBagConstraints.HORIZONTAL, GridBagConstraints.WEST);
		
		
		TitleAdd.setFont(new Font("Bookman Old Style",Font.PLAIN,25));
		SlctUser.setFont(new Font("Bookman Old Style",Font.PLAIN,20));
		
		AddPane.addComponent(TitleAdd, 0, 0, 4,2, 0, 0, GridBagConstraints.NONE, GridBagConstraints.WEST);
		Line1.setBackground(Color.BLACK);
		Line1.setEditable(false);
		AddPane.addComponent(Line1, 0, 2, 4,1, 0, 0, GridBagConstraints.HORIZONTAL, GridBagConstraints.WEST);
		ErrorAdd.setForeground(Color.RED);
		AddPane.addComponent(EnterInfo, 0, 3, 4,1, 0, 0, GridBagConstraints.HORIZONTAL, GridBagConstraints.WEST);
		AddPane.addComponent(ErrorAdd, 0, 4, 4,1, 0, 0, GridBagConstraints.HORIZONTAL, GridBagConstraints.WEST);
		AddPane.addComponent(new JLabel("User Type:"),2, 5, 1, 1, 0, 0, GridBagConstraints.NONE, GridBagConstraints.WEST);
		AddPane.addComponent(AddUserType=new JComboBox(), 3, 5, 1, 1, 0, 0, GridBagConstraints.NONE, GridBagConstraints.WEST);
		AddPane.addComponent(new JLabel("User Name: "),2, 6, 1, 1, 0, 0, GridBagConstraints.NONE, GridBagConstraints.WEST);
		AddPane.addComponent(AdduserBox=new JTextField(15), 3, 6, 1, 1, 0, 0, GridBagConstraints.NONE, GridBagConstraints.WEST);
		AddPane.addComponent(new JLabel("Password:"),2, 7, 1, 1, 0, 0, GridBagConstraints.NONE, GridBagConstraints.WEST);
		AddPane.addComponent(AddPass=new JPasswordField(15), 3, 7, 1, 1, 0, 0, GridBagConstraints.NONE, GridBagConstraints.WEST);
		AddPane.addComponent(AddBt,3, 8, 1, 1, 0, 0, GridBagConstraints.HORIZONTAL, GridBagConstraints.WEST);
		AddPane.addComponent(CheckLbl=new JLabel(""),4, 8, 1, 1, 0, 0, GridBagConstraints.HORIZONTAL, GridBagConstraints.WEST);
		AddPass.setEditable(false);
		AddBt.setEnabled(false);
		setComboBoxItems(AddUserType);
		
		UserBox=new JComboBox();
		setComboBoxItems(UserBox);
		UserList=new JList();
		setListItems(UserList);
		
		JTextArea BTA=new JTextArea(3,2);
		BTA.setBackground(Color.BLACK);
		BTA.setEditable(false);
		
		ModifyPane=new GBPane();
		ModifyPane.addComponent(SlctUser, 0, 0, 1,1, 0, 0, GridBagConstraints.HORIZONTAL, GridBagConstraints.WEST);
		ModifyPane.addComponent(UserBox, 0, 1, 1,4, 0, 0, GridBagConstraints.VERTICAL, GridBagConstraints.WEST);
		ModifyPane.addComponent(ErrorMod=new JLabel(""), 0, 6, 1,2, 0, 0, GridBagConstraints.HORIZONTAL, GridBagConstraints.WEST);
		ModifyPane.addComponent(BTA, 1, 0, 1,5, 1, 0, GridBagConstraints.VERTICAL, GridBagConstraints.WEST);
		//ModifyPane.addComponent(new JScrollPane(UserList), 0, 1, 1,5, 0, 0, GridBagConstraints.VERTICAL, GridBagConstraints.WEST);
		ModifyPane.addComponent(new JLabel("User Type:"),2, 1, 1, 1, 0, 0, GridBagConstraints.NONE, GridBagConstraints.WEST);
		ModifyPane.addComponent(UserTypeBox=new JComboBox(), 3, 1, 1, 1, 0, 0, GridBagConstraints.NONE, GridBagConstraints.WEST);
		ModifyPane.addComponent(new JLabel("User Name: "),2, 2, 1, 1, 0, 0, GridBagConstraints.NONE, GridBagConstraints.WEST);
		ModifyPane.addComponent(NameBox=new JTextField(15), 3, 2, 1, 1, 0, 0, GridBagConstraints.NONE, GridBagConstraints.WEST);
		ModifyPane.addComponent(new JLabel("Password:"),2, 3, 1, 1, 0, 0, GridBagConstraints.NONE, GridBagConstraints.WEST);
		ModifyPane.addComponent(PassBox=new JPasswordField(15), 3, 3, 1, 1, 0, 0, GridBagConstraints.NONE, GridBagConstraints.WEST);
		ModifyPane.addComponent(SaveModificationsBt, 3, 4, 1, 1, 0, 0, GridBagConstraints.NONE, GridBagConstraints.WEST);
		
		JLabel DelTitle=new JLabel("<html><h1><u>Remove User Account/s</u></h1></html>");
		DelTitle.setFont(new Font("Bookman Old Style",Font.PLAIN,25));
		DelPane=new JPanel();
		BoxLayout Bx=new BoxLayout(DelPane, BoxLayout.Y_AXIS);
		DelPane.setLayout(Bx);
		DelPane.add(DelTitle);
		//DelPane.add(new JLabel("<html><table bgcolor=\"black\"> <td> We do this today</td></table></html>"));
		DelPane.add(ErrorDel=new JLabel(""));
		DelPane.add(new JLabel("Choose A user Name"));
		setComboBoxItems(DelUserBox=new JComboBox());
		DelPane.add(DelUserBox);
		DelPane.add(DelBt);
		
		
		Right.add("AddUser", AddPane);
		Right.add("Modify",ModifyPane);
		Right.add("Delete",DelPane);
		
		AddMode.addActionListener(this);
		UpdateMode.addActionListener(this);
		DelMode.addActionListener(this);
		UserList.addListSelectionListener(this);
		AddBt.addFocusListener(this);
		DelBt.addFocusListener(this);
		SaveModificationsBt.addFocusListener(this);
		
		AdduserBox.addKeyListener(this);
		AddPass.addKeyListener(this);
		NameBox.addKeyListener(this);
		PassBox.addKeyListener(this);
	}
	
	public void setComboBoxItems(JComboBox cb){
		if(cb==UserTypeBox||cb==AddUserType){
			
			if(cb.getItemCount()<1)
				cb.removeAllItems();
			cb.addItem("Owner");
			cb.addItem("Bookkeeper");
			cb.addItem("Manager");
		}
		
		else if(cb==UserBox||cb==DelUserBox){
			//Get the users
			Users.removeAll(Users);
			try{
				ResultSet RS=Parent.getDBHandler().MySQLSelect("SELECT * from UserAccount where UserName!='"+Parent.getUser().getUserName()+"';");
				while(RS.next())
					Users.add(new User(RS.getString(1),RS.getString(2),RS.getString(3)));
				RS.close();
			}catch(Exception ex){System.out.println("Problem "+ex);}
			cb.removeAllItems();
			
			for(int ctr=0;ctr<Users.size();ctr++){
				if(!Users.get(ctr).getUserName().equals(Parent.getUser().getUserName()))
					cb.addItem(Users.get(ctr).getUserName());
				System.out.println("Added: "+Users.get(ctr).getUserName());
			}
		}
	}
	
	public void setListItems(JList L){
		Users.removeAll(Users);
		try{
			ResultSet RS=Parent.getDBHandler().MySQLSelect("SELECT * from UserAccount;");
			while(RS.next())
				Users.add(new User(RS.getString(1),RS.getString(2),RS.getString(3)));
			RS.close();
		}catch(Exception ex){System.out.println("Problem "+ex);}
		
		String[] S=new String[Users.size()];
		
		for(int ctr=0;ctr<Users.size();ctr++)
			S[ctr]=Users.get(ctr).getUserName();
		L.setListData(S);

	}
		
		
	

	@Override
	public void itemStateChanged(ItemEvent IE) {
		if(IE.getSource()==UserBox&&UserBox.getItemCount()>0){
			User Selected=Users.get(UserBox.getSelectedIndex());
			NameBox.setText(Selected.getUserName());
			PassBox.setText(Selected.getUserPassword());
			UserTypeBox.setSelectedItem(Selected.getusertype());
		}
		else SaveModificationsBt.setEnabled(true);
	}

	@Override
	public void actionPerformed(ActionEvent AE) {
		DBHandler DBH=Parent.getDBHandler();
		if(AE.getSource()==AddBt){
			String newUser=AdduserBox.getText();
			DBH.MySQLinsert("INSERT into UserAccount values('"+newUser+"','"+AddPass.getText()+"','"+AddUserType.getSelectedItem()+"');",ErrorAdd);
			setComboBoxItems(UserBox);
			setComboBoxItems(DelUserBox);
			UserBox.setSelectedItem(newUser);
			
			
			AdduserBox.setText("");
			AddPass.setText("");
			AddPass.setEditable(false);
			AddBt.setEnabled(false);
			
			if(ErrorAdd.getText().length()==0){
				CheckLbl.setIcon(Parent.getCheckImage());
				CheckLbl.setText("Insertion Complete");
			}
			SaveModificationsBt.setEnabled(false);
			
		}
		else if(AE.getSource()==DelBt){
			try {
				DBH.MySQLUpdate("DELETE FROM UserAccount where Username='"+DelUserBox.getSelectedItem()+"';");
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				ErrorDel.setForeground(Color.RED);
				ErrorDel.setText("Error in deleting");
			}
			setComboBoxItems(UserBox);
			setComboBoxItems(DelUserBox);
		}
		else if(AE.getSource()==SaveModificationsBt&&NameBox.getText().length()>0){
			User Selected=Users.get(UserBox.getSelectedIndex());
			String name=Selected.getUserName(),Pass=Selected.getUserPassword();
			try {
				DBH.MySQLUpdate("UPDATE UserAccount SET Username='"+NameBox.getText()+"',Password='"+PassBox.getText()
						+"',UserType='"+UserTypeBox.getSelectedItem()+"' WHERE Username='"+UserBox.getSelectedItem()+"';");
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				NameBox.setText(name);
				PassBox.setText(Pass);
				ErrorMod.setFont(Parent.getWarningFont(ErrorMod));
				ErrorMod.setText("Error. Modification did not occur");
				
			}
			
			String s=NameBox.getText();
			Selected.reNameUser(s);
			Selected.changePassword(PassBox.getText());
			Selected.changeUserType(UserTypeBox.getSelectedItem().toString());
			setComboBoxItems(UserBox);
			setComboBoxItems(DelUserBox);
			UserBox.setSelectedItem(s);
			setListItems(UserList);
			SaveModificationsBt.setEnabled(false);
		}
		else if(AE.getSource()==AddMode){
			AddMode.setEnabled(false);
			UpdateMode.setEnabled(true);
			CL.show(Right, "AddUser");
		}
		else if(AE.getSource()==UpdateMode){
			AddMode.setEnabled(true);
			UpdateMode.setEnabled(false);
			CL.show(Right, "Modify");
		}
		else if(AE.getSource()==DelMode)
			CL.show(Right, "Delete");
		
	}

	@Override
	public void focusGained(FocusEvent FE) {
		if(FE.getSource()==NameBox)
			ChangeTest=NameBox.getText();
		else if(FE.getSource()==PassBox)
			ChangeTest=PassBox.getText();
		focus=(JComponent) FE.getSource();
		//CheckLbl.setIcon(null);
		
	}

	@Override
	public void focusLost(FocusEvent FE) {
		ErrorMod.setText("");
		User Selected=Users.get(UserBox.getSelectedIndex());
		ErrorMod.setFont(Parent.getWarningFont(ErrorMod));
		if(NameBox.getText().length()<=0){
			NameBox.setText(ChangeTest);
			ErrorMod.setText("Modification unsaved: Don't leave textboxes empty");
		}
		else if(PassBox.getText().length()<=0){
			PassBox.setText(ChangeTest);
			ErrorMod.setText("Mofification unsaved: Don't leave textboxes empty");
		}
		else if((!Selected.getUserName().equalsIgnoreCase(NameBox.getText())&&focus==NameBox)||(!Selected.getUserPassword().equals(PassBox.getText())&&focus==PassBox))
			SaveModificationsBt.setEnabled(true);
		
		focus=null;
		CheckLbl.setIcon(null);
		CheckLbl.setText("");
		ErrorAdd.setText("");
		ErrorDel.setText("");
		
		//(ChangeTest!=NameBox.getText()&&focus==NameBox)||(ChangeTest!=PassBox.getText()&&focus==PassBox)
	}

	@Override
	public void valueChanged(ListSelectionEvent LE) {
		// TODO Auto-generated method stub
		User Selected=Users.get(UserList.getSelectedIndex());
		NameBox.setText(Selected.getUserName());
		PassBox.setText(Selected.getUserPassword());
		UserTypeBox.setSelectedItem(Selected.getusertype());
	}

	@Override
	public void keyPressed(KeyEvent KE) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void keyReleased(KeyEvent KE) {
		// TODO Auto-generated method stub
		
		
		if(!AddMode.isEnabled()){
			if(AdduserBox.getText().length()>0&&AddPass.getText().length()>0)
				AddBt.setEnabled(true);
			else if(AddPass.getText().length()==0)
				AddBt.setEnabled(false);
		
			if(AdduserBox.getText().length()>0)
				AddPass.setEditable(true);
			else AddPass.setEditable(false);
				
		}
		else if(!UpdateMode.isEnabled()){
			User Selected =Users.get(UserBox.getSelectedIndex());
			if(Selected.getUserName().equalsIgnoreCase(NameBox.getText())&&Selected.getUserPassword().equals(PassBox.getText()))
				SaveModificationsBt.setEnabled(false);
			else if (!Selected.getUserName().equalsIgnoreCase(NameBox.getText())||!Selected.getUserPassword().equals(PassBox.getText()))
				SaveModificationsBt.setEnabled(true);
		}
		
		
	}

	@Override
	public void keyTyped(KeyEvent KE) {
		
	}
}
